#include <iostream>
#include <memory>
#include "EpollServer.hpp"
#include "Log.hpp"
#include "Protocol.hpp"

protocol_ns::Response CalculateHelper(const protocol_ns::Request &req){
     //直接接入线程池
    // 走到这里，一定保证req是有具体数据的！
    // _result(result), _code(code)
    protocol_ns::Response resp(0, 0);
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
            resp._code = 2;
        else
            resp._result = req._x % req._y;
        break;
    default:
        resp._code = 3;
        break;
    }

    return resp;
}

void Calculate(Connection* conn, const protocol_ns::Request &req) {
    protocol_ns::Response resp = CalculateHelper(req);
    std::string sendStr;
    resp.Serialize(&sendStr);
    sendStr = protocol_ns::AddHeader(sendStr);

    // epoll中，关于fd读取，一般要常设置(一直要让epoll关心)
    // 关于fd的写入，按需设置，只有需要发送的时候才设置
    conn->outbuffer_ += sendStr;
    // 开启对写事件的关心
    conn->R_->EnableReadWrite(conn, true, true);
}

int main() {
    std::unique_ptr<EpollServer> svr(new EpollServer(Calculate));
    svr->InitServer();
    svr->Disptcher();
}
